package cn.edu.sdjzu.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import jakarta.annotation.PostConstruct;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class Sentinel9032Controller {
    // 进行流量控制
    @GetMapping("/hello")
    public String hello() {
        Entry entry = null;
        try {
            entry = SphU.entry("HelloWorld2");
            System.out.println("hello world666");
            return "Hello World 2";
        } catch (BlockException el) {
            System.out.println("blocked!");
            return "blocked!被流控了！";
        } catch(Exception ex) {
            // 若需要配置降级逻辑， 需要通过这种方式记录业务异常
            Tracer.traceEntry(ex, entry);
        }finally {
            if (entry != null) {
                entry.exit();
            }
        }
        return null;
    }

    // 初始化限流规则，这是spring的初始化方法
    @PostConstruct
    private static void initFlowRules() {
        List<FlowRule> rules = new ArrayList<>();  // 流控规则
        FlowRule rule = new FlowRule();
        rule.setResource("HelloWorld2"); // 设置保护的资源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // 设置流控规则为QPS。QPS（Queries Per Second）是每秒查询率
        rule.setCount(2); // 设置流控阈值
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }
}
